var chatUtil = (function(){
	/**
	 * 连接属性设置
	 */
	var setting = {
		// XMPP服务器BOSH地址
		//BOSH_SERVICE : 'http://127.0.0.1:7070/http-bind/',
		BOSH_SERVICE : 'http://chat.kaolafm.com:7070/http-bind/',
		//BOSH_SERVICE : 'http://10.10.4.20:7070/http-bind/',
		// 房间JID
		ROOM_JID : '',
		//XMPP连接发送者id
		FROMID : '',
		//XMPP连接发送者密码
		PWD : '',
		//当前状态是否连接
		CONNECTED : false,
		//连接对象
		CONNECTION : '',
		//获取消息后回调函数
		GETMSG : function(){},
		//连接断开回调函数
		CONOFF: function(){},
		//连接恢复回调函数
		CONON: function(){}
	};
	
	/**
	 * 返回属性
	 * 200：连接成功
	 * 500：连接失败
	 * 501：连接失败，获得消息回调未传入,参数名：getMsg
	 * 502：连接失败，房间id未传入,参数名：roomId
	 */
	 var result = {
		 code: 200,
		 msg: '连接成功'
	 }
	 
	 /**
	  * 状态码
	  */
	  var errorInfo = {
		  200: '连接成功',
		  500: '连接失败',
		  501: '连接失败，获得消息回调未传入,参数名：getMsg',
		  502: '连接失败，房间id未传入,参数名：roomId'
	  }
	var controller = {
		/**
		 * 初始化xmpp连接
		 */
		init: function(option){
			if({}.toString.call(option) == "[object Object]"){
				setting.BOSH_SERVICE = !util.isEmpty(option.boshService)? option.boshService : setting.BOSH_SERVICE;
				//setting.ROOM_JID = !util.isEmpty(option.roomId) ? option.roomId : '';
				setting.FROMID = !util.isEmpty(option.fromId) ? option.fromId : '';
				setting.PWD = !util.isEmpty(option.pwd) ? option.pwd : '';
				setting.CONOFF = !util.isEmpty(option.conOff)? option.conOff: setting.CONOFF;
				setting.CONON = !util.isEmpty(option.conOn)? option.conOn: setting.CONON;
				//判断roomid是否为空
				if(!util.isEmpty(option.roomId)){
					setting.ROOM_JID = option.roomId
				}else{
					result.code = 502;
					result.msg = errorInfo[502];
					return JSON.stringify(result);
				}
				//判断是否有回调消息函数
				if(!util.isEmpty(option.getMsg)){
					setting.GETMSG = option.getMsg;
					//console.info(setting.GETMSG())
					try {
						controller.startConnect();
						result.code = 200;
						result.msg = errorInfo[200];
						return JSON.stringify(result);
					} catch (error) {
						//console.info(error)
						//result.code = 500;
						//result.msg = errorInfo[500];
						//return JSON.stringify(result);
					}
					
				}else{
					result.code = 501;
					result.msg = errorInfo[501];
					return JSON.stringify(result);
				}
			}else{
				result.code = 500;
				result.msg = errorInfo[500];
				return JSON.stringify(result);
			}
		},
		
		/**
		 * 开始链接
		 */
		startConnect: function(){
			if(!setting.CONNECTED){
				setting.CONON();
				var coOption = new Object();
				coOption.callback=controller.conFailedCallBack;
				coOption.removBack=controller.conSuccessCallBack;
				setting.CONNECTION = new Strophe.Connection(setting.BOSH_SERVICE,coOption);
				setting.CONNECTION.connect(setting.FROMID, setting.PWD, controller.onConnect);
			}
		},
		
		/**
		 * 连接绑定方法
		 */
	    onConnect:function(status){
			if (status == Strophe.Status.CONNECTING) {
				return;
			} else if (status == Strophe.Status.AUTHFAIL) {
				alert("登录失败！");
			}else if (status == Strophe.Status.CONNFAIL) {
				//console.info("1---连接失败！")
				setting.CONNECTED = false;
				controller.startConnect();
			} else if (status == Strophe.Status.DISCONNECTING) {
			} else if (status == Strophe.Status.DISCONNECTED) {
				//setting.CONNECTED = false;
				//controller.startConnect();
			} else if (status == Strophe.Status.CONNECTED) {
				setting.CONNECTED = true;
				setting.CONNECTION.addHandler(controller.onMessage, null, 'message', null, null, null);
				setting.CONNECTION.send($pres().tree());
				// setting.CONNECTION.send($pres({
				// 	from: setting.FROMID,
				// 	to: setting.ROOM_JID + "/" + setting.FROMID.substring(0, setting.FROMID.indexOf("@"))
				// }).c('x', { xmlns: 'http://jabber.org/protocol/muc' }).tree());
				var fromId,showName;
				if(!util.isEmpty(setting.FROMID) && setting.FROMID.indexOf("@") > -1){
					fromId = setting.FROMID;
					showName = setting.FROMID.substring(0, setting.FROMID.indexOf("@"));
				}else{
					fromId = showName =  new Date().getTime();;
				}
				setting.CONNECTION.send($pres({
					from: fromId,
					to: setting.ROOM_JID + "/" + showName
				}).c('x', { xmlns: 'http://jabber.org/protocol/muc' }).tree());
			}
		},
		
		/**
		* 获取消息时的方法
		* @param data
		*/
		onMessage: function(data){
			console.info(data)
			var from = data.getAttribute('from');
			var fromId = "";
			if(from.indexOf("/") > -1){
				fromId = data.getAttribute('from').substring(from.indexOf("/") + 1,from.length);
			}
			var cType = data.getAttribute('type');
			var bodys = data.getElementsByTagName('body');
			if((cType == "groupchat" || cType == "chat") && bodys.length > 0){
				var body = bodys[0];
        		var msg = Strophe.getText(body);
				setting.GETMSG(msg, fromId, data);
			}
			return true;
			
		},
		
		/**
		* 发信息-单人
		* @param toId
		* @param fromId
		* @param msg
		*/
		sendMsg: function(msg, toId){
			msg = util.removeHTMLTag(msg);
			var reply = $msg({ to: toId, from: setting.FROMID, type: 'chat' }).cnode(Strophe.xmlElement('body', '', msg));
			setting.CONNECTION.send(reply.tree());
		},
		
		/**
		* 发送消息-群发
		*/
		sendMsgGroup: function(msg){
			console.info(msg);
			msg = util.removeHTMLTag(msg);
			var reply = $msg({ to: setting.ROOM_JID, from: setting.FROMID, type: 'groupchat' }).cnode(Strophe.xmlElement('body', '', msg));
    		setting.CONNECTION.send(reply.tree());
		},
		
		/**
		*断开连接回调函数 
		*/
		conFailedCallBack: function(){
			//console.info("-----------断开连接-----------");
			setting.CONOFF();
		},
		
		/**
		 * 恢复连接回调函数
		*/
		conSuccessCallBack: function(){
			//console.info("-----------恢复连接----------");
			setting.CONON;
		}
		 
	};
	
	var util = {
		/**
		 * 判断对象是否为空
		 */
		isEmpty: function(obj){
			if(obj != undefined && obj != null && obj != 'undefined' && obj != 'null' && obj != ''){
				return false;
			}
			return true;
		},
		
		/**
		 * 去除html标签
		 */
		 removeHTMLTag: function(str){
			str = str.toString();
			str = str.replace(/<\/?[^>]*>/g,' '); //去除HTML tag
			str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
			//str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
			str=str.replace(/&nbsp;/ig,'  ');//去掉&nbsp;
			return str;
		 }
		
	};
	return {
		init: controller.init,
		sendMgs: controller.sendMsg,
		sendMsgGroup: controller.sendMsgGroup
	}
})();